package cn.itcast.service.impl;

import cn.itcast.dao.MenuRepository;
import cn.itcast.dao.PermissionRepository;
import cn.itcast.dao.RoleRepository;
import cn.itcast.domain.system.Menu;
import cn.itcast.domain.system.Permission;
import cn.itcast.domain.system.Role;
import cn.itcast.domain.system.User;
import cn.itcast.service.RoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private PermissionRepository permissionRepository;
    @Autowired
    private MenuRepository menuRepository;

    @Override
    public List<Role> findByUser(User user) {
        //如果用户名为admin 则赋予全部角色
        if ("admin".equals(user.getUsername())) {
            return roleRepository.findAll();
        }
        return roleRepository.findByUserId(user.getId());
    }

    @Override
    public List<Role> findAll() {
        return roleRepository.findAll();
    }

    @Override
    public void save(Role role, String[] permissionIds, String menuIds) {
        //保存role
        roleRepository.save(role);  //利用快照自动更新到数据库
        //关联permission 先对数据进行非空判断
        if (permissionIds != null) {
            for (String permissionId : permissionIds) {
                Permission permission = permissionRepository.findOne(Integer.parseInt(permissionId));
                role.getPermissions().add(permission);
            }
        }
        //关联menu 对数据进行非空判断
        if (StringUtils.isNotBlank(menuIds)) {
            String[] menuId = menuIds.split(",");
            for (String menu : menuId) {
                Menu one = menuRepository.findOne(Integer.parseInt(menu));
                role.getMenus().add(one);
            }
        }
    }
}
